<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/accHestia/src/svr/com/acc_conn.php';

function get_accItem_property($it, $field) {
    foreach($it->attributes() as $pi => $n) {
        if($field == $pi) {
            return $n;
        }
    }
}

function single_item_process($curit, $curdep, $parentid, &$pdb) {
    $curid = get_accItem_property($curit, "id");
    $curname = get_accItem_property($curit, "name");
    
    $ssql = "select id from account where serialNo = " . $parentid;
    $pid = $pdb->qw($ssql, "id");
    
    $firstNum = substr($curid, 0, 1); //1:资产(借)  2:负债  3:所有者权益  4:成本费用(借) 5:收入
    if(1 == $firstNum || 4 == $firstNum) {
        $balanceDirect = "cr";
    } else {
        $balanceDirect = "de";
    }
    
    $ssql = "insert into account(level, parentId, serialNo, name, balanceDirect) values('" . $curdep . "', '" . $pid . "', '" . $curid . "', '" . $curname . "', '" . $balanceDirect . "')";
    if(!$pdb->q($ssql)) {
        exit ("ERROR! when insert acc no:" . $curid . ", name:" . $curname . "<br/> " . $db->get_error());
    }
}

function r_read_accItem($acc_item_root, $depth, &$pdb) {
    if(0 == sizeof($acc_item_root->accItem)) {
        return;
    }
    ++$depth;
    
    foreach($acc_item_root->accItem as $it) {
        $itid = get_accItem_property($acc_item_root, "id");
        if("" == $itid) {
            $itid = 0;
        }
        single_item_process($it, $depth, $itid, $pdb);
        r_read_accItem($it, $depth, $pdb);
    }
}

function buildacc_by_category($cate, $xmlpath) {
    $xml = simplexml_load_file($xmlpath);
    $pdb = new acc_DB();
    //$pdb->c();
    //$pdb->s();
    
    foreach($xml as $ids) {
        $curcate = "";
        foreach($ids->attributes() as $a => $b) {
            $curcate = $b;
        }
        if($curcate == $cate) {
            $mydepth = 0;
            r_read_accItem($ids, $mydepth, $pdb);
            break;
        }
    }
    //$pdb->d();
}
?>
